<?php
 namespace app\dao;

 /**
 * @desc 拆装单单头
 */
 use app\dao\BaseDAO;
 use Yii;
 use app\enum\EnumOther;
 use yii\db\Query;
	
 class DisassemblyDetailDAO extends BaseDAO
 {
	/**
	 * @desc 构造函数
	 * @author liaojianwen
	 * @date 2017-10-17
	 * @return DisassemblyDetailDAO
	 */
	public function __construct()
	{
		parent::__construct();
		$this->_table = 'disassembly_detail';
		$this->_pKey ='disassembly_det_id';
	}

	/**
	 * @inheritdoc
	 */
	public static function tableName()
	{
		return '{{%disassembly_detail}}';
	}
	
	/**
	 * @desc 编辑页面拆装单明细数据
	 * @author liaojianwen
	 * @date 2017-04-01
	 */
	public function getDisassemblyDetail($id)
	{
		$selects = "disassembly_det_id,d.disassembly_id,d.type,d.product_id,d.quantity,d.remark,p.product_name,p.product_sn,s.warehouse_out,s.warehouse_in,
				d.quantity_unit,d.price,d.amount,base_quantity,base_unit,u.unit_name base_name,second_quantity,second_unit,second_relation,p.unit_content";
		$conditions ="d.disassembly_id = :id and d.delete_flag = :flag";
		$params = [
				':id'=>$id,
				':flag'=>EnumOther::NO_DELETE,
		];
		$query = new Query();
		$result = $query->select($selects)
		->from("$this->_table d")
		->leftJoin("product p",'d.product_id = p.product_id')
		->leftJoin("unit u","u.unit_id = d.base_unit")
		->leftJoin("disassembly s","s.disassembly_id = d.disassembly_id")
		->where($conditions,$params)
		->all();
		foreach ($result as &$res){
			$res_units = ProductUnitDAO::getInstance()->getUnits($res['product_id'] );
			$res['product_unit'] = $res_units;
			if($res['type'] == 0){
				$res_quantity = StockPileDAO::getInstance()->findByAttributes('quantity','product_id = :pid and warehouse_id =:wid',[':pid'=>$res['product_id'],':wid'=>$res['warehouse_out']]);
			} else if($res['type'] == 1) {
				$res_quantity = StockPileDAO::getInstance()->findByAttributes('quantity','product_id = :pid and warehouse_id =:wid',[':pid'=>$res['product_id'],':wid'=>$res['warehouse_in']]);
			}
			$res['product_quantity'] = isset($res_quantity['quantity']) ? $res_quantity['quantity']:0;
		}
		return $result;
	
	}
 }